using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Threading;
using System.Data.SqlClient;

namespace AssetCapture
{
    public partial class WaitingForm : Form
    {
        public delegate void ResumeForm();
        ResumeForm formStart;
        string m_ConnectionString;
        bool m_Close;

        public WaitingForm(string sqlConnection, ResumeForm formFunc)
        {
            InitializeComponent();
            formStart = formFunc;
            m_ConnectionString = sqlConnection;

            m_Close = false;

            ThreadStart ts = new ThreadStart(WaitDone);
            Thread t = new Thread(ts);
            t.Start();

            timer1.Start();
            timer1.Tick += new EventHandler(timer1_Tick);
        }

        void timer1_Tick(object sender, EventArgs e)
        {
            if (m_Close)
                this.Close();
        }

        private void WaitDone()
        {
            string command = "select value from GlobalConfig where Property = 'FTPBatchStopping'";
            bool stopping = Convert.ToBoolean(getDataObject(command));

            while (stopping)
            {
                Thread.Sleep(1000);
                stopping = Convert.ToBoolean(getDataObject(command));
            }

            formStart();
            m_Close = true;
        }

        //Get the SQL command and return single object item using DataReader to speed up the communication
        public object getDataObject(string selectSQL)
        {
            SqlConnection con = new SqlConnection(m_ConnectionString);
            SqlCommand cmd = new SqlCommand(selectSQL, con);
            SqlDataReader reader = null;
            object ob = new object();

            try
            {
                con.Open();
                reader = cmd.ExecuteReader();
                reader.Read();
                if (reader.HasRows)
                    ob = reader[0];//Only read ONE data in the first of list
                else
                    ob = 0;
                reader.Close();

            }
            catch (SqlException err)
            {
                //if (err.Number != 1205)
                    //MessageBox.Show("Error occur while connect to DataBase via DataReader, Check Connection : \n" + err);
            }
            finally
            {
                con.Close();
            }
            return ob;

        }
    }
}